<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:insert="~{include :: header('添加关联需求')}" />
    <th:block th:insert="~{include :: select2-css}" />
    <style>
        .relation-form {
            padding: 20px;
        }
        .relation-type-group {
            margin-bottom: 20px;
        }
        .relation-type-badge {
            margin-right: 5px;
            padding: 3px 8px;
            font-size: 12px;
        }
        .search-issue-section {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #e7eaec;
            border-radius: 5px;
        }
        .issue-search-results {
            max-height: 300px;
            overflow-y: auto;
            margin-top: 10px;
        }
        .issue-result-item {
            padding: 8px 10px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
        }
        .issue-result-item:hover {
            background-color: #f5f5f5;
        }
        .issue-result-item.selected {
            background-color: #e6f7ff;
            border-left: 3px solid #1890ff;
        }
        .relation-description {
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="relation-form">
        <form id="form-relation-add" class="form-horizontal">
            <input type="hidden" id="issueId" th:value="${issueId}" />
            
            <!-- 关联类型选择 -->
            <div class="relation-type-group">
                <label class="control-label"><strong>关联类型:</strong></label>
                <div class="form-group">
                    <div class="btn-group" data-toggle="buttons">
                        <label class="btn btn-default active">
                            <input type="radio" name="relationType" value="relates" checked="checked" />
                            <span class="label label-default relation-type-badge">关联</span>
                        </label>
                        <label class="btn btn-default">
                            <input type="radio" name="relationType" value="duplicates" />
                            <span class="label label-warning relation-type-badge">重复</span>
                        </label>
                        <label class="btn btn-default">
                            <input type="radio" name="relationType" value="blocks" />
                            <span class="label label-danger relation-type-badge">阻塞</span>
                        </label>
                        <label class="btn btn-default">
                            <input type="radio" name="relationType" value="follows" />
                            <span class="label label-info relation-type-badge">跟随</span>
                        </label>
                        <label class="btn btn-default">
                            <input type="radio" name="relationType" value="precedes" />
                            <span class="label label-success relation-type-badge">前置</span>
                        </label>
                    </div>
                </div>
            </div>

            <!-- 需求搜索 -->
            <div class="search-issue-section">
                <div class="form-group">
                    <label class="control-label"><strong>选择关联需求:</strong></label>
                    <div class="input-group">
                        <input type="text" id="issueSearch" class="form-control" placeholder="输入需求ID或主题进行搜索..." />
                        <span class="input-group-btn">
                            <button type="button" class="btn btn-primary" onclick="searchIssues()">搜索</button>
                        </span>
                    </div>
                </div>
                
                <div id="issueSearchResults" class="issue-search-results" style="display: none;">
                    <!-- 搜索结果将在这里显示 -->
                </div>
                
                <div id="selectedIssueInfo" style="display: none; margin-top: 15px; padding: 10px; background-color: #f8f9fa; border-radius: 4px;">
                    <strong>已选择需求:</strong>
                    <span id="selectedIssueText"></span>
                    <input type="hidden" id="relatedIssueId" />
                </div>
            </div>

            <!-- 关联描述 -->
            <div class="relation-description">
                <div class="form-group">
                    <label class="control-label"><strong>关联描述 (可选):</strong></label>
                    <textarea id="relationDescription" class="form-control" rows="3" placeholder="请输入关联描述..."></textarea>
                </div>
            </div>

            <div class="form-group text-center" style="margin-top: 30px;">
                <button type="button" class="btn btn-primary" onclick="submitRelation()">添加关联</button>
                <button type="button" class="btn btn-default" onclick="$.modal.close()">取消</button>
            </div>
        </form>
    </div>

    <th:block th:insert="~{include :: footer}" />
    <script>
        var prefix = ctx + "project/issue";
        var selectedIssue = null;

        // 搜索需求
        function searchIssues() {
            var keyword = $('#issueSearch').val().trim();
            if (!keyword) {
                $.modal.msgWarning('请输入搜索关键词');
                return;
            }

            $.ajax({
                url: prefix + "/list",
                type: "POST",
                data: {
                    subject: keyword
                },
                dataType: "json",
                success: function(result) {
                    if (result.code == 0 && result.rows && result.rows.length > 0) {
                        displaySearchResults(result.rows);
                    } else {
                        $('#issueSearchResults').html('<div class="text-center" style="padding: 20px;"><small class="text-muted">未找到相关需求</small></div>').show();
                    }
                },
                error: function() {
                    $.modal.msgError('搜索失败，请稍后再试');
                }
            });
        }

        // 显示搜索结果
        function displaySearchResults(issues) {
            var html = '';
            var currentIssueId = $('#issueId').val();
            
            issues.forEach(function(issue) {
                // 排除当前需求本身
                if (issue.id == currentIssueId) {
                    return;
                }
                
                var statusColor = issue.issueStatus ? issue.issueStatus.htmlColor : '52C41A';
                var priorityClass = issue.priority ? issue.priority.listClass : 'default';
                
                html += '<div class="issue-result-item" data-issue-id="' + issue.id + '" onclick="selectIssue(this, ' + JSON.stringify(issue).replace(/"/g, '&quot;') + ')">';
                html += '<div class="row">';
                html += '<div class="col-sm-8">';
                html += '<strong>#' + issue.id + '</strong> ' + (issue.subject || '未知主题');
                html += '</div>';
                html += '<div class="col-sm-4 text-right">';
                html += '<span class="label label-' + statusColor + '" style="margin-right: 5px;">' + (issue.statusName || '未知状态') + '</span>';
                html += '<span class="label label-' + priorityClass + '">' + (issue.priorityName || '未知优先级') + '</span>';
                html += '</div>';
                html += '</div>';
                html += '<div class="row" style="margin-top: 5px;">';
                html += '<div class="col-sm-12 text-muted">';
                html += '<small>项目: ' + (issue.projectName || '未知项目') + ' | 指派给: ' + (issue.assignedToName || '未指派') + '</small>';
                html += '</div>';
                html += '</div>';
                html += '</div>';
            });

            $('#issueSearchResults').html(html).show();
        }

        // 选择需求
        function selectIssue(element, issue) {
            $('.issue-result-item').removeClass('selected');
            $(element).addClass('selected');
            
            selectedIssue = issue;
            
            $('#selectedIssueText').html(
                '<strong>#' + issue.id + '</strong> ' + (issue.subject || '未知主题') + 
                ' <span class="label label-' + (issue.issueStatus ? issue.issueStatus.htmlColor : '52C41A') + '">' + (issue.statusName || '未知状态') + '</span>'
            );
            $('#relatedIssueId').val(issue.id);
            $('#selectedIssueInfo').show();
        }

        // 提交关联
        function submitRelation() {
            var issueId = $('#issueId').val();
            var relatedIssueId = $('#relatedIssueId').val();
            var relationType = $('input[name="relationType"]:checked').val();
            var description = $('#relationDescription').val().trim();
            
            if (!relatedIssueId) {
                $.modal.msgWarning('请选择要关联的需求');
                return;
            }
            
            if (issueId == relatedIssueId) {
                $.modal.msgWarning('不能关联需求本身');
                return;
            }
            
            $.ajax({
		        url: ctx + "issue/relation/add/" + issueId,
                type: "POST",
                data: {
                    relatedIssueId: relatedIssueId,
                    relationType: relationType,
                    description: description
                },
                dataType: "json",
                success: function(result) {
                    if (result.code == 0) {
                        $.modal.msgSuccess("关联添加成功");
                        // 刷新父页面
                        if (window.parent && window.parent.loadRelations) {
                            window.parent.loadRelations(issueId);
                        }
                        $.modal.close();
                    } else {
                        $.modal.msgError(result.msg || "关联添加失败");
                    }
                },
                error: function() {
                    $.modal.msgError("关联添加失败，请稍后再试");
                }
            });
        }

        // 回车键搜索
        $(document).ready(function() {
            $('#issueSearch').keypress(function(e) {
                if (e.which == 13) {
                    searchIssues();
                    return false;
                }
            });
        });
    </script>
</body>
</html>